/*
 * cs_cli.cpp
 *
 *  Created on: Sep 13, 2016
 *      Author: ubuntu
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <iostream>
#include "common.h"

using namespace std;

int cli_port = 12980;
char *cli_host = NULL;
int sv_fd = 0;

#define PROG_NAME	"cs_cli"


static void parse_cmd(int argc, char **argv);

int main(int argc, char **argv)
{
	parse_cmd(argc, argv);
	printf(PROG_NAME "> ");
	fflush(stdout);
	char buf[1024];
	sv_fd = connect_server(cli_host, cli_port, 5);
	if (sv_fd < 0) {
		perror("connect_server");
		return -1;
	}
	while (fgets(buf, sizeof(buf), stdin)) {
		if (strncasecmp(buf, "exit", 4) == 0 ||
				strncasecmp(buf, "quit", 4) == 0)
		{
			printf("Exit\n");
			break;
		} else if (strncmp(buf, "clear", 5) == 0) {
			system("clear");
		} else {
			while (buf[strlen(buf)-1] == '\n')
				buf[strlen(buf)-1] = 0;
			write(sv_fd, buf, strlen(buf));
		}
		printf(PROG_NAME "> ");
		fflush(stdout);
	}
	return 0;
}

static void parse_cmd(int argc, char **argv)
{
	int c;
	while ((c = getopt(argc, argv, "p:h:")) != -1) {
		switch (c) {
		case 'p':
			if  (optarg) {
				cli_port = atoi(optarg);
			}
			break;
		case 'h':
			if (optarg) {
				if (cli_host)
					free(cli_host);
				cli_host = strdup(optarg);
			}
			break;
		default:
			break;
		}
	}
}

